package com.kura.uednews.dantri;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import android.util.Log;

public class UedHandler extends DefaultHandler {
	NewsFeed feed;
	NewsItem item;

	boolean feedTitleHasBeenRead = false;
	boolean feedPubDateHasBeenRead = false;

	boolean isTitle = false;
	boolean isDescription = false;
	boolean isLink = false;
	boolean isPubDate = false; ;

	String des = "";
	String title = "";
	String pubDate = "";
	String link = "";

	String titleTmp = "";
	String descTmp = "";
	String linkTmp = "";
	String pubTmp = "";	

	public UedHandler() {

	}

	public NewsFeed getFeed() {
		return feed;
	}

	public void startDocument() throws SAXException {
		
		if(feed == null){
			feed = new NewsFeed();
		}
		item = new NewsItem(); // an item to temporarily store feed data
	}

	public void endDocument() throws SAXException {
	}

	public void startElement(String namespaceURI, String localName,
			String qName, Attributes atts) throws SAXException {

		if (qName.equals("item")) {
			// create a new item
			item = new NewsItem();
			return;
		} else if (qName.equals("title")) {
			isTitle = true;
			return;
		} else if (qName.equals("description")) {
			isDescription = true;
			return;
		} else if (qName.equals("link")) {
			isLink = true;
			return;
		} else if (qName.equals("pubDate")) {
			isPubDate = true;
			return;
		} else if (qName.equals("guid")) {

		}
	}

	public void endElement(String namespaceURI, String localName, String qName)
			throws SAXException {
		if (qName.equals("item")) {
			feed.addItem(item);
			return;
		} else if (qName.equals("description")) {
			isDescription = false;
			item.setDescription(des);
			des = "";
			return;
		} else if (qName.equals("title")) {
			isTitle = false;
			item.setTitle(title);
			title = "";
			return;
		} else if (qName.equals("pubDate")) {
			isPubDate = false;
			item.setPubDate(pubDate);
			pubDate = "";
			return;
		} else if (qName.equals("link")) {
			isLink = false;
			item.setLink(link);
			link = "";
			return;
		}else if(qName.equals("title")){
			isTitle = false;
			if(titleTmp.length() > 81){
				titleTmp = titleTmp.substring(0, 81).toLowerCase() +"...";
			}
			titleTmp = titleTmp.substring(0,1) + titleTmp.substring(1).toLowerCase();
			item.setTitle(titleTmp);
			titleTmp = "";
		}
		else if(qName.equals("link")){
			isLink = false;
			item.setLink(linkTmp);
			linkTmp = "";
		}
	}

	public void characters(char ch[], int start, int length) {
		String s = new String(ch, start, length);

		if (isTitle) {
			title += s;
		} else if (isLink) {
			link += s;
		} else if (isDescription) {
			des += s;
		} else if (isPubDate) {
			pubTmp += s;
		}
	}
}
